package com.nai365.nart.common.base.service.impl;

import cn.hutool.core.util.IdUtil;
import com.nai365.nart.common.base.service.FileService;
import com.nai365.nart.common.core.util.R;
import com.nai365.nart.common.file.core.FileProperties;
import com.nai365.nart.common.file.core.FileTemplate;
import com.nai365.nart.common.file.oss.OssProperties;
import com.nai365.nart.common.file.oss.service.OssTemplate;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
@AllArgsConstructor
public class FileServiceImpl implements FileService {

	private final FileProperties fileProperties;

	private final FileTemplate fileTemplate;

	/**
	 * 上传文件
	 * @param file
	 * @return
	 */
	@Override
	public R uploadFile(MultipartFile file) {
		String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		String dir = format + "/";

		String fileName = dir+IdUtil.simpleUUID() + file.getOriginalFilename();
		Map<String, String> resultMap = new HashMap<>(4);
		resultMap.put("bucketName", fileProperties.getBucketName());
		resultMap.put("fileName", fileName);
		resultMap.put("url", "http://"+fileProperties.getBucketName()+"."+fileProperties.getOss().getEndpoint()+"/"+fileName);

		try {
			fileTemplate.putObject(fileProperties.getBucketName(), fileName, file.getInputStream());
			// 文件管理数据记录,收集管理追踪文件
		}
		catch (Exception e) {
			log.error("上传失败", e);
			return R.failed(e.getLocalizedMessage());
		}
		return R.ok(resultMap);
	}
}
